Scope, Constants
var vs let
tip
- Variables declared with var have function scope.(Var变量具有函数作用域)
- the temporal dead zone(零时死区)
如果在函数内使用 var 声明变量,Javascript 引擎会将它们视为在函数作用域的顶部声明。但是,如果该变量已在函数外部声明,则无论实际声明发生在何处,它都具有全局作用域。这就是所谓的吊装。
function logAge() {
console.log( 'age:', age ); // 这里会输出undefined
var age = 25;
}
logAge();
name会报错,而var不会
function logName() {
console.log( 'name:', name ); // ReferenceError: name is not defined
let name = 'Ben';
}
logName();
danger
作为完整的参考,let、const 和 class 声明存在临时死区。对于 var 、 function 和 function* 声明来说,它不存在。
const
tip
Declarations with const are block scoped, they have to be initialized, and their value cannot be changed after initialization.(申明必须初始化,之后不可改变)
const PI = 3.1415;
PI = 3.14; // error
let, const, and var
tip
- Rule 1: use let for variables, and const for constants whenever possible. Use var only when you have to maintain legacy code.(尽量用let,除非祖传代码)
- Rule 2: Always declare and initialize all your variables at the beginning of your scope.(每次在作用域顶部定义变量)